<template>
  <el-dialog
    class="goods-dialog-class"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :before-close="handleClose"
    :title="tips"
    width="30%"
    top="2vh"
  >
    <el-form
      ref="formRef"
      label-width="150px"
      label-position="top"
      class="demo-dynamic"
      :rules="rules"
      :model="formData"
    >
      <el-form-item prop="product_name" label="商品名称">
        <el-input v-model="formData.product_name" auto-complete="off" />
      </el-form-item>
      <el-form-item label="种类id" prop="category_id">
        <el-select v-model="formData.category_id">
          <el-option
            v-for="(item, i) in options"
            :label="item.category_name"
            :value="item.category_id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="product_title" label="商品标题">
        <el-input v-model="formData.product_title" />
      </el-form-item>
      <el-form-item prop="product_intro" label="商品介绍">
        <el-input v-model="formData.product_intro" />
      </el-form-item>
      <el-form-item label="商品封面图片路径" prop="product_picture">
        <el-upload
          v-model:file-list="formData.product_picture"
          :show-file-list="true"
          :limit="1"
          ref="upload"
          :on-exceed="handleExceed"
          list-type="picture"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="
            (proData == 'development' ? '/api' : pUrl) + '/product/UploadProduct'
          "
          class="avatar-uploader"
        >
          <el-button type="primary"> 上传商品主图</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品标价" prop="product_price">
        <el-input-number
          v-model="formData.product_price"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="商品售价" prop="product_selling_price">
        <el-input-number
          v-model="formData.product_selling_price"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="商品库存" prop="product_num">
        <el-input-number
          v-model="formData.product_num"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item
        v-if="tips == '修改商品'"
        :prop="tips == '修改商品' ? 'product_up_down' : ''"
        label="商品上下架"
      >
        <el-radio-group v-model="formData.product_up_down">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="cancelDialog">取消</el-button>
        <el-button type="primary" @click="handleLogin"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  ref,
  getCurrentInstance,
  reactive,
  defineExpose,
  defineEmits,
} from "vue";
import { addProduct, getCategory, modifyProduct } from "@/api/services";
import { genFileId } from "element-plus";
import {productUrl} from '@/utils/request'

const emit = defineEmits(["refresh"]);
const { proxy } = getCurrentInstance();
const formRef = ref();
const pUrl = ref(productUrl);
const options = ref([]);
const proData = ref(process.env.NODE_ENV);
let formData = reactive({
  product_name: "",
  category_id: undefined,
  product_title: "",
  product_intro: "",
  product_up_down: "",
  product_picture: [],
  product_price: undefined,
  product_selling_price: undefined,
  product_num: undefined,
});
const rules = reactive({
  product_up_down: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  product_name: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  product_title: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  product_intro: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  category_id: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  product_picture: [
    {
      required: true,
      message: "请上传商品封面",
      trigger: "change",
    },
  ],
  product_price: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  product_selling_price: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  product_num: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
});
const open = async (title, user = {}) => {
  // console.log("user: ", user);
  dialogVisible.value = true;
  tips.value = title;
  const res = await getCategory();
  options.value = res.category;
  if (user.product_name) {
    let data = {
      ...user,
      product_picture: [
        {
          url:
            (proData.value == "development" ? "/api" : pUrl.value+"/") +
            user.product_picture,
          name: user.product_picture.substr(
            user.product_picture.lastIndexOf("public/") + 7,
          ),
        },
      ],
    };
    formData = Object.assign(formData, data);
  } else {
  }
};
const handleLogin = () => {
  if (!formRef) return;
  //   console.log('formRef: ', formRef);
  formRef.value.validate(async (valid, fields) => {
    if (valid) {
      // console.log("submit!", formData);
      let res;
      let params = {
        ...formData,
        product_picture:
          "public/imgs/public/" + formData.product_picture[0].name,
      };
      if (tips.value == "新增商品") {
        res = await addProduct(params);
      } else {
        res = await modifyProduct(params);
      }
      // console.log("res: ", res);
      proxy.$message.success(res.msg);
      emit("refresh");
      cancelDialog();
    } else {
      // console.log("error submit!", fields);
    }
  });
};

const dialogVisible = ref(false);
const tips = ref("新增商品");
const upload = ref();

const cancelDialog = () => {
  formData = Object.assign(formData, {
    product_name: "",
    category_id: "",
    product_title: "",
    product_intro: "",
    product_up_down: "",
    product_picture: [],
    product_price: undefined,
    product_selling_price: undefined,
    product_num: undefined,
  });
  formRef.value.resetFields();
  dialogVisible.value = false;
};
const handleClose = done => {
  formData = Object.assign(formData, {
    product_name: "",
    category_id: "",
    product_title: "",
    product_intro: "",
    product_up_down: "",
    product_picture: [],
    product_price: undefined,
    product_selling_price: undefined,
    product_num: undefined,
  });
  formRef.value.resetFields();
  done();
};

const handleExceed = files => {
  if (formData.product_picture.length >= 1) {
    proxy.$message.error("请先删除!");
    return;
  }
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
};
//上传封面成功调用的方法
const handleAvatarSuccess = (res, file) => {
  // console.log("res: ", res, file);
  if (res.code == 2) {
    proxy.$message.error(res.msg);
    formData = Object.assign(formData, { product_picture: [] });
  } else {
  }
};
//上传之前调用的方法
const beforeAvatarUpload = file => {
  // console.log("file: ", formData.product_picture.length >= 1);
  if (formData.product_picture.length >= 1) {
    proxy.$message.error("请先删除!");
    return false;
  }
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    proxy.$message.error("上传商品封面只能是 JPG、PNG 格式!");
  }
  if (!isLt2M) {
    proxy.$message.error("上传商品封面大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};

//关键点 把 方法暴露给父组件
defineExpose({ open });
</script>

<style>
.goods-dialog-class .el-dialog__body {
  padding-left: 40px;
}
.goods-dialog-class .el-dialog__body .el-form .el-input-number,
.goods-dialog-class .el-dialog__body .el-form .el-select {
  width: 100%;
}
.goods-dialog-class
  .el-dialog__body
  .el-form
  .el-input-number
  .el-input__inner {
  text-align: left;
}
</style>
